package gmodel

import (
	"context"
	"fmt"
	"gitee.com/851537/gmodel/rds"
	jsoniter "github.com/json-iterator/go"
	"github.com/redis/go-redis/v9"
	"reflect"
	"time"
)

// 通用缓存器,独立基类,供实体类继承使用
// 对 BaseRedisCount 的升级，支持自定义key，不限制子类的GetId()方法
type BaseRedisCache struct {
}

// 参数child必须为指针类型
func (this *BaseRedisCache) redisCacheName(child IBase, key string) string {
	return fmt.Sprintf("UCache.%s.%s", reflect.ValueOf(child).Elem().Type().Name(), key)
}

func (this *BaseRedisCache) getCmd(child IBase, key string) *redis.StringCmd {
	return rds.ClientIns().Get(context.Background(), this.redisCacheName(child, key))
}

// 默认不过期
func (this *BaseRedisCache) SetRedisCache(child IBase, key string, content interface{}, expireTime ...int64) error {
	var (
		expire int64
		err    error
	)
	if len(expireTime) > 0 {
		expire = expireTime[0]
	}
	_, err = rds.ClientIns().Set(context.Background(), this.redisCacheName(child, key), content, time.Duration(expire)*time.Second).Result()
	return err
}

func (this *BaseRedisCache) GetRedisCache(child IBase, key string) string {
	return this.getCmd(child, key).Val() //String()
}

func (this *BaseRedisCache) GetRedisCacheTo(child IBase, key string, container any) (err error) {
	str := this.GetRedisCache(child, key)
	if str == "" {
		return
	}
	return jsoniter.UnmarshalFromString(this.GetRedisCache(child, key), container)
	//return container.FromX(container, this.GetRedisCache(child, key))
}

func (this *BaseRedisCache) GetRedisCacheInt(child IBase, key string) int {
	v, err := this.getCmd(child, key).Int()
	if err != nil {
		return 0
	}
	return v
}

func (this *BaseRedisCache) GetRedisCacheInt64(child IBase, key string) int64 {
	v, err := this.getCmd(child, key).Int64()
	if err != nil {
		return 0
	}
	return v
}

func (this *BaseRedisCache) GetRedisCacheFloat64(child IBase, key string) float64 {
	v, err := this.getCmd(child, key).Float64()
	if err != nil {
		return 0
	}
	return v
}

// 删除缓存
func (this *BaseRedisCache) DelRedisCache(child IBase, key string) error {
	return rds.ClientIns().Del(context.Background(), this.redisCacheName(child, key)).Err()
}